package com.ijava.base.service.impl;


import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ijava.base.dao.UserGroupDAO;
import com.ijava.base.domain.UserGroup;
import com.ijava.base.service.UserGroupService;

public class UserGroupServiceImpl implements UserGroupService {
	private static final Logger logger = LoggerFactory.getLogger(UserGroupServiceImpl.class);
	private UserGroupDAO dao;

	public UserGroupDAO getDao() {
		return dao;
	}

	public void setDao(UserGroupDAO dao) {
		this.dao = dao;
	}

	public void remove(String id) throws Exception {
		dao.remove(id);
	}

	public void mutilRemove(UserGroup userGroup) throws Exception {
		try {
			String[] keys = userGroup.getKeys();
			if(null == keys)
				return;
			for (int i = 0; i < keys.length; i++) {
				remove(keys[i]);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

	public void save(UserGroup userGroup) throws Exception {
		dao.save(userGroup);
	}

	public void update(UserGroup userGroup) throws Exception {
		dao.update(userGroup);
	}

	public void saveOrUpdate(UserGroup userGroup) throws Exception {
		dao.saveOrUpdate(userGroup);
	}

	public UserGroup get(String id) throws Exception {
		return dao.get(id);
	}

	public List findWithPaging(UserGroup userGroup) throws Exception {
		try {
			int firstRow = (userGroup.getPageNo() - 1)
					* userGroup.getPageSize();
			int maxRow = userGroup.getPageSize();

			List paramList = new ArrayList();
			StringBuffer condition = new StringBuffer(" where 1 = 1 ");
			if (StringUtils.hasLength(userGroup.getGroupCode())) {
				condition.append(" and groupCode like ?");
				paramList.add("%" + userGroup.getGroupCode() + "%");
			}
			if (StringUtils.hasLength(userGroup.getGroupName())) {
				condition.append(" and groupName like ?");
				paramList.add("%" + userGroup.getGroupName() + "%");
			}
			if (StringUtils.hasLength(String.valueOf(userGroup.getRowEnable()))) {
				condition.append(" and rowEnable = ?");
				paramList.add(userGroup.getRowEnable());
			}

			int total = dao.find(
					"select count(*) from " + UserGroup.class.getName()
							+ condition.toString(), paramList).size();
			userGroup.setTotal(total);

			String queryString = "from " + UserGroup.class.getName()
					+ condition.toString();
			return dao.findWithPaging(queryString, paramList, firstRow, maxRow);
		} catch (Exception e) {
			logger.error("", e);
			throw e;
		}
	}

}
